﻿
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Collections.Generic;
using EnterpriseServices.DalEf;
using System.ServiceModel.Activation;

namespace EnterpriseServices.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class RoleServiceREST : RoleServiceBase, IRoleManagerREST
    {
        #region IRoleManagerREST Members
        /// <summary>
        /// Adds the specified userNames to the specified roleName.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userNames">The userName names.</param>
        /// <param name="roleName">The roleName.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "POST", UriTemplate = "/AddUsersToRole/{applicationName};{userNames};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.AddUsersToRole(string applicationName, string userNames, string roleName)
        {     
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(userNames))
                throw new FaultException("userNames is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");
           
            try
            {
                base.AddUsersToRole(applicationName,
                                                     Converters.StringCsvToStringList(userNames),
                                                     roleName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Adds the specified userNames to the specified roleNames.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userNames">The userName names.</param>
        /// <param name="roleNames">The roleNames.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "POST", UriTemplate = "/AddUsersToRoles/{applicationName};{userNames};{roleNames}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.AddUsersToRoles(string applicationName, string userNames, string roleNames)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (userNames == null || userNames.Length == 0)
                throw new FaultException("userNames is null or empty.");
            if (roleNames == null || roleNames.Length == 0)
                throw new FaultException("roleNames is null or empty.");

            try
            {
                base.AddUsersToRoles(applicationName, 
                                                       Converters.StringCsvToStringList(userNames), 
                                                       Converters.StringCsvToStringList(roleNames));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Adds the specified userName to the specified roleName.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userName">Name of the userName.</param>
        /// <param name="roleName">The roleName.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "POST", UriTemplate = "/AddUserToRole/{applicationName};{userName};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.AddUserToRole(string applicationName, string userName, string roleName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");

            try
            {
                base.AddUserToRole(applicationName, userName.Replace("-", "\\"), roleName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Adds the specified userName to the specified roleNames.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userName">Name of the userName.</param>
        /// <param name="roleNames">The roleNames.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "POST", UriTemplate = "/AddUserToRoles/{applicationName};{userName};{roleNames}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.AddUserToRoles(string applicationName, string userName, string roleNames)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            if (roleNames == null || roleNames.Length == 0)
                throw new FaultException("roleNames is null or empty.");

            try
            {
                base.AddUserToRoles(applicationName, 
                                                     userName.Replace("-", "\\"), 
                                                     Converters.StringCsvToStringList(roleNames));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Adds a new roleName to the data source.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="roleName">The roleName.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "POST", UriTemplate = "/CreateRole/{applicationName};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.CreateRole(string applicationName, string roleName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");

            try
            {
                base.CreateRole(applicationName, roleName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Removes a roleName from the data source. If throwOnPopulatedRole is true,throws an exception if roleName has one or more members.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="roleName">The roleName.</param>
        /// <param name="throwOnPopulatedRole">if set to <c>true</c> [throw on populated roleName].</param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "DELETE", UriTemplate = "/DeleteRole/{applicationName};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IRoleManagerREST.DeleteRole(string applicationName, string roleName, string throwOnPopulatedRole)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");

            try
            {
                return base.DeleteRole(applicationName, roleName, Convert.ToBoolean(throwOnPopulatedRole));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

        /// <summary>
        /// Removes all the roleNames from the data source. If throwOnPopulatedRole is true,throws an exception if any of the roleNames has one or more members
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="throwOnPopulatedRole">if set to <c>true</c> [throw on populated roleName].</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "DELETE", UriTemplate = "/DeleteAllRoles/{applicationName};{throwOnPopulatedRole}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.DeleteAllRoles(string applicationName, string throwOnPopulatedRole)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");

            try
            {
                base.DeleteAllRoles(applicationName, Convert.ToBoolean(throwOnPopulatedRole));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Gets a list of all the roleNames for the applicationName.
        /// </summary>
        /// <param name="applicationName"></param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/GetAllRoles/{applicationName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        String[] IRoleManagerREST.GetAllRoles(string applicationName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");

            try
            {
                List<Role> myRoleList = base.GetAllRoles(applicationName);
                int myCount = myRoleList.Count;
                int i = 0;
                String[] myStringList = new String[myCount];

                myRoleList.ForEach(r =>
                {
                    myStringList[i] = r.RoleName.ToString();
                    i += 1;
                });
                return myStringList;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return null;
            }
        }

        /// <summary>
        /// Gets a list of the roleNames that a userName is in.
        /// </summary>
        /// <param name="applicationName"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/GetRolesByUser/{applicationName};{userName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        String[] IRoleManagerREST.GetRolesByUser(string applicationName, string userName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");

            try
            {
                List<Role> myRoleList = base.GetRolesByUser(applicationName, userName.Replace("-", "\\"));
                int myCount = myRoleList.Count;
                int i = 0;
                String[] myStringList = new String[myCount];

                myRoleList.ForEach(r =>
                {
                    myStringList[i] = r.RoleName.ToString();
                    i += 1;
                });
                return myStringList;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return null;
            }
        }

        /// <summary>
        /// Gets a list of userNames in the specified roleName.
        /// </summary>
        /// <param name="applicationName"></param>
        /// <param name="roleName"></param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/GetUsersInRole/{applicationName};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        String[] IRoleManagerREST.GetUsersInRole(string applicationName, string roleName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");

            try
            {
                List<User> myUserList = base.GetUsersInRole(applicationName, roleName);
                int myCount = myUserList.Count;
                int i = 0;
                String[] myStringList = new String[myCount];

                myUserList.ForEach(ur =>
                {
                    myStringList[i] = ur.UserName.ToString();
                    i += 1;
                });
                return myStringList;
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return null;
            }
        }

        /// <summary>
        /// Removes the specified userName from the specified roleName.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userName">Name of the userName.</param>
        /// <param name="roleName">Name of the roleName.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "DELETE", UriTemplate = "/RemoveUserFromRole/{applicationName};{userName};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.RemoveUserFromRole(string applicationName, string userName, string roleName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");

            try
            {
                base.RemoveUserFromRole(applicationName, userName.Replace("-", "\\"), roleName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Removes the specified userNames from the specified roleName.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userNames">The userNames.</param>
        /// <param name="roleName">The roleName.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "DELETE", UriTemplate = "/RemoveUsersFromRole/{applicationName};{userNames};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.RemoveUsersFromRole(string applicationName, string userNames, string roleName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (userNames == null || userNames.Length == 0)
                throw new FaultException("userNames is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");

            try
            {
                base.RemoveUsersFromRole(applicationName, 
                                                                 Converters.StringCsvToStringList(userNames), 
                                                                 roleName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Removes the specified userName from the specified roleNames.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userName">The userName.</param>
        /// <param name="roleNames">The roleNames.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "DELETE", UriTemplate = "/RemoveUserFromRoles/{applicationName};{userName};{roleNames}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.RemoveUserFromRoles(string applicationName, string userName, string roleNames)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(userName))
                throw new FaultException("userName is null or empty.");
            if (roleNames == null || roleNames.Length == 0)
                throw new FaultException("roleNames is null or empty.");

            try
            {
                base.RemoveUserFromRoles(applicationName, 
                                                                 userName.Replace("-", "\\"), 
                                                                 Converters.StringCsvToStringList(roleNames));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Removes the specified userName names from the specified roleNames.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="userNames">The userNames.</param>
        /// <param name="roleNames">The roleNames.</param>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = true)]
        [WebInvoke(Method = "DELETE", UriTemplate = "/RemoveUsersFromRoles/{applicationName};{userNames};{roleNames}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        void IRoleManagerREST.RemoveUsersFromRoles(string applicationName, string userNames, string roleNames)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (userNames == null || userNames.Length == 0)
                throw new FaultException("userNames is null or empty.");
            if (roleNames == null || roleNames.Length == 0)
                throw new FaultException("roleNames is null or empty.");

            try
            {
                base.RemoveUsersFromRoles(applicationName, 
                                                                   Converters.StringCsvToStringList(userNames), 
                                                                   Converters.StringCsvToStringList(roleNames));
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }

        /// <summary>
        /// Returns true if roleName management is enabled; otherwise,false
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <returns>
        /// 	<c>true</c> if [is roleNames enabled] [the specified applicationName]; otherwise, <c>false</c>.
        /// </returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/IsRolesEnabled/{applicationName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IRoleManagerREST.IsRolesEnabled(string applicationName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");

            try
            {
                return base.IsRolesEnabled(applicationName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

        /// <summary>
        /// Returns true if the roleName name already exists in the data source; otherwise,false.
        /// </summary>
        /// <param name="applicationName">The applicationName.</param>
        /// <param name="roleName">The roleName.</param>
        /// <returns></returns>
        [TransactionFlow(TransactionFlowOption.Allowed)]
        [OperationBehavior(TransactionScopeRequired = false)]
        [WebGet(UriTemplate = "/RoleExists/{applicationName};{roleName}", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]
        bool IRoleManagerREST.RoleExists(string applicationName, string roleName)
        {
            if (String.IsNullOrEmpty(applicationName))
                throw new FaultException("applicationName is null or empty.");
            if (String.IsNullOrEmpty(roleName))
                throw new FaultException("roleName is null or empty.");

            try
            {
                return base.RoleExists(applicationName, roleName);
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("EnterpriseServices", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }
        }

        #endregion
    }
}
